package com.yanqu.sync.demo;

import com.yanqu.sync.demo.dispatcher.PendingCenter;
import com.yanqu.sync.demo.dispatcher.Service;
import com.yanqu.sync.demo.entity.Request;
import com.yanqu.sync.demo.entity.Response;

import java.time.Duration;
import java.time.ZonedDateTime;
import java.util.Arrays;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class Main {
    public static void main( String[] args )
    {

        int loopTimes = 10;
        CountDownLatch countDownLatch = new CountDownLatch(loopTimes);

        ExecutorService executorService = Executors.newFixedThreadPool(1);

        ZonedDateTime startTime = ZonedDateTime.now();
        for (int i = 0; i < loopTimes; i++) {
            Request request = new Request();
            request.setSequenceId(i);
            executorService.execute(new Runnable() {
                @Override
                public void run() {
                    System.out.printf("client----req:%s----thread:%s----, time: %s\n", request.getSequenceId(), Thread.currentThread().getId(), ZonedDateTime.now());
                    CompletableFuture<Response> responseFuture = PendingCenter.send(request);
                    responseFuture.thenAccept( response -> {
                        System.out.printf("----req:%s----thread:%s----, time: %s\n", request.getSequenceId(), Thread.currentThread().getId(), ZonedDateTime.now());
                        System.out.printf("----req:%s----res:%s----\n", request.getSequenceId(), response.getSequenceId());
                        countDownLatch.countDown();
                    });

                }
            });
        }

        try {
            countDownLatch.await();
        } catch (InterruptedException e) {
            System.out.println(Arrays.toString(e.getStackTrace()));
        }
        executorService.shutdown();
        Service.shutDown();
        ZonedDateTime endTime = ZonedDateTime.now();
        long millis = Duration.between(startTime, endTime).toMillis();
        System.out.printf("isDone, %d", millis);
    }
}
